// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#pragma once

#include <pollux/dwio/common/seekable_input_stream.h>
#include <pollux/dwio/dwrf/common/wrap/dwrf-proto-wrapper.h>
#include <pollux/type/type.h>

namespace kumo::pollux::dwrf {

class ProtoUtils final {
 public:
  static void writeType(
      const Type& type,
      proto::Footer& footer,
      proto::Type* parent = nullptr);

  static std::shared_ptr<const Type> fromFooter(
      const proto::Footer& footer,
      std::function<bool(uint32_t)> selector = [](uint32_t) { return true; },
      uint32_t index = 0);

  // Deserialize proto from inputStream. Caller can optionally pass in the
  // object to serialize to.
  template <typename T>
  static std::unique_ptr<T> readProto(
      std::unique_ptr<dwio::common::SeekableInputStream> stream,
      std::unique_ptr<T> ret = nullptr) {
    if (!ret) {
      ret = std::make_unique<T>();
    }
    DWIO_ENSURE(
        ret->ParseFromZeroCopyStream(stream.get()),
        "Failed to parse proto from ",
        stream->getName());
    return ret;
  }

  // Reads 'stream' into the pre-existing proto 'ret'. Use this
  // instead of readProto when the proto is arena-allocated since
  // moving an arena proto via unique_ptr would be confusing since it
  // is not owned by the unique_ptr.
  template <typename T>
  static T* readProtoInto(
      std::unique_ptr<dwio::common::SeekableInputStream> stream,
      T* ret) {
    DWIO_ENSURE(ret);
    DWIO_ENSURE(
        ret->ParseFromZeroCopyStream(stream.get()),
        "Failed to parse proto from ",
        stream->getName());
    return ret;
  }
};

} // namespace kumo::pollux::dwrf
